<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');



class MY_Session extends CI_Session{

	public function __construct($params = array())
	{
        parent::__construct($params);
    }
    
	/**
	 * Update an existing session
	 * Override this method in reason to add the update the user session activity
     *
	 * @access	public
	 * @return	void
     * 
	 */
	function sess_update()
	{
        log_message('debug', 'Start - '. __METHOD__);
		// We only update the session every five minutes by default
		if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
		{
            log_message('debug', 'STOP - '. __METHOD__." : ".$this->userdata['last_activity']." + ".$this->sess_time_to_update.') >= '.$this->now);
			return;
		}

		// Save the old session id so we know which record to
		// update in the database if we need it
		$old_sessid = $this->userdata['session_id'];
		$new_sessid = '';
		while (strlen($new_sessid) < 32)
		{
			$new_sessid .= mt_rand(0, mt_getrandmax());
		}

		// To make the session ID even more secure we'll combine it with the user's IP
		$new_sessid .= $this->CI->input->ip_address();

		// Turn it into a hash
		$new_sessid = md5(uniqid($new_sessid, TRUE));

		// Update the session data in the session data array
		$this->userdata['session_id'] = $new_sessid;
		$this->userdata['last_activity'] = $this->now;

		// _set_cookie() will handle this for us if we aren't using database sessions
		// by pushing all userdata to the cookie.
		$cookie_data = NULL;

		// Update the session ID and last_activity field in the DB if needed
		if ($this->sess_use_database === TRUE)
		{
			// set cookie explicitly to only have our session data
			$cookie_data = array();
			foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
			{
                log_message('debug',"Update Session:".$this->userdata[$val]);
				$cookie_data[$val] = $this->userdata[$val];
			}

			$this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
            
		}
        // @win Update the User login status.
        // Do this to prevent user from login-in on multiple browser.
        
        
        
//        if (!class_exists('acl_auth')){
//            log_message('error', 'Acl_auth not loaded????????');
//            $this->load->library('acl_auth');
//        }
        if ($this->userdata('logged_in')){
            log_message('debug','Client currently login:('.$this->userdata("account_name").':'.$this->userdata("user_id").') and updating activity');
            // NOTE: if you update the this section, please find to update.
            // Acl_aut::activateCurrentLogin
            $time=time();
            $update['login_expired']=$time+60*30; // added 30 mins
            $update['last_activity']=$time;
            $this->CI->db->query(
                    $this->CI->db->update_string(
                            'users',
                            $update,
                    array('id' => $this->userdata("user_id"))));
        }
        log_message('debug', 'End - '. __METHOD__);
		// Write the cookie
		$this->_set_cookie($cookie_data);
	}

    
	/**
	 * Write the session cookie
	 *
     * @override To read the session expiry on custom cofiguration.
	 * @access	public
	 * @return	void
     * @author Win
	 */
	function _set_cookie($cookie_data = NULL)
	{
		if (is_null($cookie_data))
		{
			$cookie_data = $this->userdata;
		}

		// Serialize the userdata for the cookie
		$cookie_data = $this->_serialize($cookie_data);

		if ($this->sess_encrypt_cookie == TRUE)
		{
			$cookie_data = $this->CI->encrypt->encode($cookie_data);
		}

		$cookie_data .= hash_hmac('sha1', $cookie_data, $this->encryption_key);

		//$expire = ($this->sess_expire_on_close === TRUE) ? 0 : $this->sess_expiration + time();
                $this->CI->load->library('configuration');
        $expire = $this->CI->configuration->getSessionExpiration()*60+  time();         
        log_message('debug',__METHOD__.' - SessionExpiration: '.$expire."(".time().")");
		$expire = ($this->sess_expire_on_close === TRUE) ? 0 :  $expire;

		// Set the cookie
        //log_message('error', __METHOD__.' -> Set Cookie: '.$this->sess_cookie_name." <=> ".$cookie_data);
        if (!preg_match('/GT-P3110/',$_SERVER['HTTP_USER_AGENT'])){
            setcookie(
                $this->sess_cookie_name,
                $cookie_data,
                $expire,
                $this->cookie_path,
                $this->cookie_domain,
                $this->cookie_secure
            );
        }else{
            // Facsheet the Tablet na yan. ayaw mga sent ng cookie
            setcookie(
                $this->sess_cookie_name,
                $cookie_data,
                $expire,
                // time()+60*60*24*2, // 2days
                "/"
    //			$this->cookie_domain,
    //			$this->cookie_secure
            );
        }
	}
    
}
